<?php
function insert($table,$fields_arr)
{
	global $conn;
	if(!$conn){return false;}
	$strfields="";
	$strvalues="";
	list($key, $val) = each($fields_arr);
	if(is_string($key)){
		$strfields = " ($key";
		$strvalues= $val;
		while(list($key, $val) = each($fields_arr)){
			$strfields.= ", $key";
			$strvalues.= ",".$val;
		}
			$strfields.=")";
	}else{
		$strvalues=$fields_arr[0];
		for($i=1;$i<(count($fields_arr));$i++){
			$strvalues .= ", $fields_arr[$i]";
		}
	}
	
	$query = "INSERT INTO $table $strfields VALUES ($strvalues)";
	return mysql_query($query, $conn);
}


function update($table, $fields_arr, $where) 
{
	global $conn;
	if (!$conn) 
    { 
        return false; 
    }
	list($key, $val) = each($fields_arr);
	$strset=" $key = $val";
	while(list($key, $val) = each($fields_arr))
    {
		$strset .= ", $key = $val";
	}
	$query = "UPDATE $table SET $strset WHERE $where"; 
	$result = mysql_query($query, $conn);
	return !$result ? false : true;
}

function delete_rows($table, $fields_arr, $where_ext = "") 
{
	global $conn;
	if (!$conn) 
    { 
        return false; 
    }
	if(count($fields_arr) > 0)
    {
		list($key, $val) = each($fields_arr);
		$strwhere=" $key = $val";
		while(list($key, $val) = each($fields_arr))
        {
			$strwhere .= "OR $key = $val";
		}
	}
	
	$query = "DELETE FROM $table WHERE $strwhere $where_ext";      
	$result = mysql_query($query, $conn);
	if (!$result) 
    {
        return false;
    }
	return true;
}

function check_mail($email)
{
    if(!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $email)) 
        return false;
	return true;
}

function countRecord($table, $where = null)
{
    global $conn;
    if($table == null)
        return false;
    if($where == null)
        $where = "1 = 1";
    $result = mysql_query("Select count(*) as cnt From $table Where $where", $conn);
    $row = @mysql_fetch_assoc($result);
    return $row['cnt'];
}

function countPages($total, $n)
{
    if($total % $n == 0)
    {
        return (int)($total / $n);
    }
    return (int)($total / $n) + 1;
}

function createPage($total, $link, $nitem, $itemcurrent, $step = 10)
{
    if($total < 1)
    {
        return false;
    }
    $ret = "";
    $param = "";
    $pages = countPages($total, $nitem);
    if($itemcurrent > 0)
    {
        $ret .= '<a title="Next" href="'. $link . '0">[&lt;]</a>';
    }
    if($itemcurrent > 1)
    {
        $ret .= '<a title="Previous" href="'. $link . ($itemcurrent + 1) . '">[&lt;]</a>';
    }
    $from = ($itemcurrent - $step > 0 ? $itemcurrent - $step : 0);
    $to = ($itemcurrent + $step < $pages ? $itemcurrent + $step : $pages);
    for($i=$from; $i<$to; $i++)
    {
        if($i != $itemcurrent)
        {
            $ret .= '<a href="'. $link . $i .'">' . ($i + 1) . '</a>';
        }
        else
        {
            $ret .= '<b>' . ($i + 1) . '</b>';
        }
    }
    if(($itemcurrent < $pages - 2) && ($pages > 1))
    {
        $ret .= '<a title="Next" href="'. $link . ($itemcurrent + 1). '">[&gt;]</a> ';
    }
    if ($itemcurrent < $pages-1)
    {
        $ret .= '<a title="End" href="' .$link. ($pages-1). '">[&gt;&gt;]</a>';    
    }  
	return $ret;
}

function getFileExtension($filename)
{
    return strrchr($filename, ".");
}

function checkUpload($f, $ext="", $maxsize=0, $req=0)
{
    $fname = strtolower(basename($f['name']));
    $ftemp = $f['tmp_name'];
    $fsize = $f['size'];
    $fext = getFileExtension($fname);
    if($fsize == 0)
    {
        if($req == 0)
        {
            return "Chọn file upload";
        }
        return "";
    }
    else
    {
        if($ext != "")
        {
            if(strpos($ext, $fext) === false)
            {
                return "$fname không được để rỗng";
            }
            if($maxsize > 0) if($fsize > $maxsize)
            {
                return "Không thể ".$maxsize." byte";
            }
        }
    }
    return "";
}

function makeUpload($f, $newfile)
{
    if(move_uploaded_file($f['tmp_name'], $newfile))
    {
        return $newfile;
    }
    return false;
}

/////////////////////////////////////////////CATEGORY////////////////////////////////////////////////////////
function getCategoryList()
{
    global $conn;
    $result = mysql_query("Select * From mid_categories", $conn);
    $ret = array();
    while($row = mysql_fetch_assoc($result))
    {
        $ret[] = $row;
    }
    return $ret;
}

function getCatSelectList($current_cat_id, $count) 
{
    global $conn;
    static $option_results;

    // if there is no current category id set, start off at the top level (zero)
    if (!isset($current_cat_id)) 
    {
        $current_cat_id =0;
    }

    // increment the counter by 1
    $count = $count+1;

    // query the database for the sub-categories of whatever the parent category is
    $sql =  'SELECT id, category_name From mid_categories Where parent_id =  '.$current_cat_id;
    $sql .=  'order by category_name asc ';

    $get_options = mysql_query($sql, $conn);
    $num_options = mysql_num_rows($get_options);

    // our category is apparently valid, so go ahead €¦
    if ($num_options > 0) 
    {
        while (list($cat_id, $cat_name) = mysql_fetch_row($get_options)) 
        {
            // if its not a top-level category, indent it to
            //show that its a child category
            if ($current_cat_id != 0) 
            {
                $indent_flag =  '--';
                for ($x=2; $x<=$count; $x++) 
                {
                    $indent_flag .=  ' >';
                }
            }
            $cat_name = $indent_flag.$cat_name;
            $option_results[$cat_id] = $cat_name;

            // now call the function again, to recurse through the child categories
            getCatSelectList($cat_id, $count );
        }
    }
    return $option_results;
}

function getListCategory($catid = "", $split = "=")
{
    global $con;
    $ret = array();
    if ($catid == "") 
        $catid = 0;
	$result = mysql_query("Select * From mid_categories Where status = 0 and parent_id = $catid ",$con);
    while ($row = mysql_fetch_assoc($result))
	{
		$ret[] = array($row['id'],($catid == 0 ? "" : $split).$row['category_name']);
		$getsub = getListCategory($row['id'], $split.$split);
		foreach ($getsub as $sub)
			$ret[] = array($sub[0], $sub[1]);
  	}
	return $ret;
}

function getCategory($parentId=0)
{
    global $conn;
    $sql = mysql_query("Select * From mid_categories Where parent_id = " . $parentId, $conn);
    $categoryData = array();
    while($row = mysql_fetch_array($sql))
    {
        $categoryData['id'][] = $row['id'];
        $categoryData['category_name'][] = $row['category_name']; 
    }
    return $categoryData;
}

function getArrayCategory($table, $parentId = "", $split = "=")
{
    global $conn;
    $hide = "status = 0";
    $ret = array();
    if ($catid == "") 
        $catid = 0;
	$result = @mysql_query("Select * From $table Where $hide And parent_id = $parentId", $conn);
	while($row = mysql_fetch_assoc($result))
    {
		$ret[] = array($row['id'], ($parentId == 0 ? "" : $split) . $row['category_name']);
		$getsub = getArrayCategory($table, $row['id'], $split.$split);
		foreach ($getsub as $sub)
			$ret[] = array($sub[0],$sub[1]);
	}
	return $ret;
}

function getArrayCategoryChild($table, $catid = "", $split = "=")
{
    global $conn;
    $hide = "status=0";
    $ret = array();
    if ($catid == "") 
        $catid = 1;
	$result = @mysql_query("Select * From $table Where $hide and parent_id = $catid", $conn);
	while($row=mysql_fetch_assoc($result))
    {
		$ret[] = array($row['id'], ($catid == 2 ? "" : $split) . $row['category_name']);
		$getsub = getArrayCategory($table, $row['id'], $split.$split);
		foreach ($getsub as $sub)
			$ret[] = array($sub[0], $sub[1]);
	}
	return $ret;
}

/////////////////////////////////GET COUNTY LIST//////////////////////////////////////////////
function getCountryList($index, $name="country", $class="textbox")
{
	$arrValue = array(
		'Afghanistan','Albania','Algeria','American Samoa','Andorra','Angola','Anguilla','Antarctica','Antigua and Barbuda','Argentina','Armenia','Aruba','Australia','Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus',
		'Belgium','Belize','Benin','Bermuda','Bhutan','Bolivia','Bosnia and Herzegowina','Botswana','Bouvet Island','Brazil','British Indian Ocean Territory','British Virgin Islands','Brunei Darussalam','Bulgaria','Burkina Faso','Burundi','Cambodia','Cameroon','Canada','Cape Verde',
		'Cayman Islands','Central African Republic','Chad','Chile','China','Christmas Island','Cocos (Keeling) Islands','Colombia','Comoros','Congo','Cook Islands','Costa Rica','Cote D\'ivoire','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Djibouti','Dominica',
		'Dominican Republic','East Timor','Ecuador','Egypt','El Salvador','Equatorial Guinea','Eritrea','Estonia','Ethiopia','Falkland Islands (Malvinas)','Faroe Islands','Fiji','Finland','France','France, Metropolitan','French Guiana','French Polynesia','French Southern Territories','Gabon','Gambia',
		'Georgia','Germany','Ghana','Gibraltar','Greece','Greenland','Grenada','Guadeloupe','Guam','Guatemala','Guinea','Guinea-Bissau','Guyana','Haiti','Heard and McDonald Islands','Honduras','Hong Kong','Hungary','Iceland','India',
		'Indonesia','Iraq','Ireland','Islamic Republic of Iran','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kiribati','Korea','Korea, Republic of','Kuwait','Kyrgyzstan','Laos','Latvia','Lebanon','Lesotho',
		'Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Madagascar','Malawi','Malaysia','Maldives','Mali','Malta','Marshall Islands','Martinique','Mauritania','Mauritius','Mayotte','Mexico','Micronesia',
		'Moldova, Republic of','Monaco','Mongolia','Montserrat','Morocco','Mozambique','Myanmar','Namibia','Nauru','Nepal','Netherlands','Netherlands Antilles','New Caledonia','New Zealand','Nicaragua','Niger','Nigeria','Niue','Norfolk Island','Northern Mariana Islands',
		'Norway','Oman','Pakistan','Palau','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Pitcairn','Poland','Portugal','Puerto Rico','Qatar','Reunion','Romania','Russian Federation','Rwanda','Saint Lucia','Samoa',
		'San Marino','Sao Tome and Principe','Saudi Arabia','Senegal','Serbia and Montenegro','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa','Spain','Sri Lanka','St. Helena','St. Kitts and Nevis','St. Pierre and Miquelon','St. Vincent and the Grenadines','Sudan',
		'Suriname','Svalbard and Jan Mayen Islands','Swaziland','Sweden','Switzerland','Syrian Arab Republic','Taiwan','Tajikistan','Tanzania, United Republic of','Thailand','Togo','Tokelau','Tonga','Trinidad and Tobago','Tunisia','Turkey','Turkmenistan','Turks and Caicos Islands','Tuvalu','Uganda',
		'Ukraine','United Arab Emirates','United Kingdom (Great Britain)','United States','United States Virgin Islands','Uruguay','Uzbekistan','Vanuatu','Vatican City State','Venezuela','Vietnam','Wallis And Futuna Islands','Western Sahara','Yemen','Zaire','Zambia'
	);			
	$arrText = array(
		'Afghanistan','Albania','Algeria','American Samoa','Andorra','Angola','Anguilla','Antarctica','Antigua and Barbuda','Argentina','Armenia','Aruba','Australia','Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus',
		'Belgium','Belize','Benin','Bermuda','Bhutan','Bolivia','Bosnia and Herzegowina','Botswana','Bouvet Island','Brazil','British Indian Ocean Territory','British Virgin Islands','Brunei Darussalam','Bulgaria','Burkina Faso','Burundi','Cambodia','Cameroon','Canada','Cape Verde',
		'Cayman Islands','Central African Republic','Chad','Chile','China','Christmas Island','Cocos (Keeling) Islands','Colombia','Comoros','Congo','Cook Islands','Costa Rica','Cote D\'ivoire','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Djibouti','Dominica',
		'Dominican Republic','East Timor','Ecuador','Egypt','El Salvador','Equatorial Guinea','Eritrea','Estonia','Ethiopia','Falkland Islands (Malvinas)','Faroe Islands','Fiji','Finland','France','France, Metropolitan','French Guiana','French Polynesia','French Southern Territories','Gabon','Gambia',
		'Georgia','Germany','Ghana','Gibraltar','Greece','Greenland','Grenada','Guadeloupe','Guam','Guatemala','Guinea','Guinea-Bissau','Guyana','Haiti','Heard and McDonald Islands','Honduras','Hong Kong','Hungary','Iceland','India',
		'Indonesia','Iraq','Ireland','Islamic Republic of Iran','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kiribati','Korea','Korea, Republic of','Kuwait','Kyrgyzstan','Laos','Latvia','Lebanon','Lesotho',
		'Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Madagascar','Malawi','Malaysia','Maldives','Mali','Malta','Marshall Islands','Martinique','Mauritania','Mauritius','Mayotte','Mexico','Micronesia',
		'Moldova, Republic of','Monaco','Mongolia','Montserrat','Morocco','Mozambique','Myanmar','Namibia','Nauru','Nepal','Netherlands','Netherlands Antilles','New Caledonia','New Zealand','Nicaragua','Niger','Nigeria','Niue','Norfolk Island','Northern Mariana Islands',
		'Norway','Oman','Pakistan','Palau','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Pitcairn','Poland','Portugal','Puerto Rico','Qatar','Reunion','Romania','Russian Federation','Rwanda','Saint Lucia','Samoa',
		'San Marino','Sao Tome and Principe','Saudi Arabia','Senegal','Serbia and Montenegro','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa','Spain','Sri Lanka','St. Helena','St. Kitts and Nevis','St. Pierre and Miquelon','St. Vincent and the Grenadines','Sudan',
		'Suriname','Svalbard and Jan Mayen Islands','Swaziland','Sweden','Switzerland','Syrian Arab Republic','Taiwan','Tajikistan','Tanzania, United Republic of','Thailand','Togo','Tokelau','Tonga','Trinidad and Tobago','Tunisia','Turkey','Turkmenistan','Turks and Caicos Islands','Tuvalu','Uganda',
		'Ukraine','United Arab Emirates','United Kingdom (Great Britain)','United States','United States Virgin Islands','Uruguay','Uzbekistan','Vanuatu','Vatican City State','Venezuela','Vietnam','Wallis And Futuna Islands','Western Sahara','Yemen','Zaire','Zambia'
	);
	$firstValue = "[Chọn quốc gia]";
	$out = '';
	$out .= '<select name="'.$name.'" id="'.$name.'" class="'.$class.'">';
	$out .= '<option value="-1">'.$firstValue.'</option>';
	for($i=0; $i<count($arrValue); $i++){
		$selected = $arrValue[$i] == $index ? 'selected' : '';
		$out .= '<option value="'.$arrValue[$i].'" '.$selected.'>'.$arrText[$i].'</option>';
	}
	$out .= '</select>';
	return $out;
}